<script lang="tsx" setup>
import { isNumber } from '@vc/utils';
import { setHrefUrlTool } from '../../../../../../utils';
import { getPermitReportF9 } from '../../../apis';
import PageHeader from '../../../components/page-header.vue';
import ErrorModule from '../../../components/error-module.vue';
import { useF9Context } from '../../../use/use-context';
import Tabs from '../components/tabs.vue';
import IndicatorSource from '@/components/indicator-source/index.vue';

interface Props {
  /** 标题名称 */
  title: string;
  /** 标题 id */
  menuId: string;
  /** 数值 */
  count: number | null;
}

const { title, menuId, count } = defineProps<Props>();


const activeTab = ref(0);

let tableData = ref<any[]>([]);
/** 废气 index */
let gasIndex = ref<Set<number[]>>(new Set([]));
let wastewaterIndex = ref<Set<number[]>>(new Set([]));
const { companyId } = useF9Context();
const { data, loading, error } = useRequest(getPermitReportF9, {
  defaultParams: [{ id: companyId }],
  onSuccess: (res) => {
    res?.items.forEach((item, index) => {
      tableData.value[index] = [];
      gasIndex.value[index] = 0;
      wastewaterIndex.value[index] = 0;
      item.actualDischarge.forEach((sub_item) => {
        sub_item.gasReportList?.forEach((child_item) => {
          handleTabledata(sub_item, child_item, index, true, false);
        });
        
        sub_item.waterReportList?.forEach(child_item => {
          handleTabledata(sub_item, child_item, index, false, true);
        });
      });
      
      if (gasIndex.value[index]) {
        tableData.value[index].unshift({
          pollutants: '<div class="infos"><span class="title">废气 </span><span class="desc">全厂合计(t/a)</span></div>'
        });
      }
      
      if (wastewaterIndex.value[index]) {
        tableData.value[index].splice(gasIndex.value[index] ? gasIndex.value[index] + 1 : 0, 0, {
          pollutants: '<div class="infos"><span class="title">废水 </span><span class="desc">全厂合计(t/a)</span></div>'
        });
      }
    });
  }
});

function handleTabledata (sub_item, child_item, index, isGas, isWater) {
  const item_index = tableData.value?.[index]?.findIndex(item => item.pollutants === child_item.pollutants);
  
  const child_data = {
    ['yearEmissionAmount' + sub_item.reportYear]: child_item.yearEmissionAmount,
    ['yearEmissionAmountLimit' + sub_item.reportYear]: child_item.yearEmissionAmountLimit,
    ['rate' + sub_item.reportYear]: child_item.rate,
    ['fileCode' + sub_item.reportYear]: child_item.fileCode,
    ['fileType' + sub_item.reportYear]: child_item.fileType,
    ['fileUrl' + sub_item.reportYear]: child_item.fileUrl,
    ['locationInDocument' + sub_item.reportYear]: child_item.locationInDocument,
    ['positioning' + sub_item.reportYear]: child_item.positioning
  };
  
  if (isNumber(item_index) && item_index !== -1) {
    tableData.value[index][item_index] = {
      ...tableData.value[index][item_index],
      pollutants: child_item.pollutants,
      ...child_data
    };
  } else {
    if (isGas) {
      gasIndex.value[index]++;
    }
    if (isWater) {
      wastewaterIndex.value[index]++;
    }
    
    tableData.value[index].push({
      pollutants: child_item.pollutants,
      ...child_data
    });
  }
}

const columns = computed(() => {
  return (item) => {
    return [
      { field: 'yearEmissionAmountLimit' + item.reportYear, title: '许可排放量' },
      { field: 'yearEmissionAmount' + item.reportYear, title: '实际排放量' },
      { field: 'rate' + item.reportYear, title: '实际许可比', noSource: true }
    ];
  };
});

/** 溯源 */
let isTraceSource = $ref(false);

/** 是否展开 */
const isExpand = ref(false);

/** 初始最多展示数据量  */
const maxNumber = 8;

function goSource (actionData, yearData) {
  setHrefUrlTool(
    actionData['fileType' + yearData],
    actionData['fileUrl' + yearData],
    '',
    '',
    actionData['positioning' + yearData]
  );
}

const showJump = computed(() => {
  return (row, item, sub_item) => {
    return isTraceSource && row['fileUrl' + item.reportYear] && !sub_item.noSource;
  };
});
</script>

<template>
  <page-header class="my-15px" :count="count" :title="title" :menuId="menuId" is-small />
  <template v-if="data?.items?.length">
    <error-module v-if="error" :error="error" />
    <tabs v-else :tabsData="data?.items" :activeTab="activeTab" tabName="licenceNo">
      <template #default="slot">
        <vxe-table
          class="complex-table"
          v-if="tableData?.[slot.index]?.length"
          border="inner"
          :loading="loading"
          ref="xTable"
          align="center"
          :auto-resize="true"
          :merge-cells="[
          { row: 0, col: 0, rowspan: 1, colspan: data?.items?.[0]?.actualDischarge?.length * 3 + 1 },
          { row: gasIndex[slot.index] + 1, col: 0, rowspan: 1, colspan: data?.items?.[slot.index]?.actualDischarge?.length * 3 + 1 },
          ]"
          :data="tableData[slot.index].slice(0, isExpand ? tableData[slot.index].length : maxNumber)">
          <vxe-colgroup title="年度" align="left">
            <vxe-column type="html" field="pollutants" title="类型" width="150px" />
          </vxe-colgroup>
          <vxe-colgroup :title="item.reportYear + '年'"
            v-for="(item, index) in data?.items?.[slot.index]?.actualDischarge" :key="index">
            <vxe-column :min-width="100" :field="sub_item.field" :title="sub_item.title"
              v-for="(sub_item, sub_index) in columns(item)" :key="sub_index">
              <template #default="{ row }">
              <span v-if="row[sub_item.field] || row[sub_item.field] === 0"
                :class="[showJump(row, item, sub_item) ? 'common-link' : '']"
                @click="showJump(row, item, sub_item) ? goSource(row, item.reportYear) : () => {}"
              >
                {{ row[sub_item.field] }}
              </span>
                <span v-else>-</span>
              </template>
            </vxe-column>
          </vxe-colgroup>
        </vxe-table>
        <div class="w-full text-center mt-10px">
          <el-button size="small" v-if="tableData[slot.index]?.length > maxNumber"
            @click="isExpand = !isExpand" style="background: rgba(2, 198, 128, 0.10); color: #02C680; border-color: rgba(2, 198, 128, 0.10);">
            {{ isExpand ? '收起' : '展开更多' }}
            <vc-icon icon="vi-arrow-down" color="#02C680" :class="[isExpand ? 'rotate-180' : '']" />
          </el-button>
        </div>
      </template>
      <template #tabsRight>
      <div class="flex align-center">
        <div class="w-30px text-13px text-#666666">溯源</div>
        <el-switch
          v-model="isTraceSource"
          class="ml-2"
          size="small"
          style="--el-switch-on-color: #02C680; margin-top: 2px;"
        />
      </div>
      </template>
    </tabs>
  </template>
  <vc-nodata v-else :type="200"/>
</template>

<style lang="scss" scoped>
:deep(.complex-table) {
  .vxe-header--row:first-child {
    .vxe-header--column {
      padding: 9px 0px;
      font-weight: 400;
      font-size: 13px;
      color: #666666;
    }
    background: rgba(231, 247, 243, 0.30);
  }

  .vxe-header--row:last-child {
    .vxe-header--column {
      padding: 9px 0px;
      font-weight: 400;
      font-size: 13px;
      color: #666666;
    }

    background: rgba(231, 247, 243, 0.30);
    th:first-child {
      text-align: left;
    }
  }

  .vxe-body--row {
    .vxe-body--column {
      padding: 6px 0px;
      font-weight: 400;
      font-size: 13px;
      color: #111;
    }

    .vxe-body--column[colspan] {
      .vxe-cell {
        text-align: left;
      }
    }
  }

  .infos {
    font-size: 13px;

    .title {
      color: #fa993b;
      font-weight: 500;
    }

    .desc {
      color: #666666;
      font-weight: 400;
      font-size: 12px;
      margin-left: 3px;
    }
  }
}
:deep(.vxe-table) {
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #F6F6F6 !important;
}
:deep(th.vxe-header--column) {
  border-right: 1px solid #F6F6F6 !important;
}
:deep(.vxe-body--column) {
  border-right: 1px solid #F6F6F6 !important;
}
</style>
